﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace GenBenEditor
{
    public struct TileId
    {
        public byte tileset;
        public byte tile;

        public TileId(byte tileset, byte tile)
        {
            this.tileset = tileset;
            this.tile = tile;
        }

        public UInt16 ToUInt16()
        {
            return (UInt16)(tile >> 8 | tileset);
        }

        public void FromUInt16(UInt16 tid)
        {
            tile = (byte)((tid & 0xFF00) >> 8);
            tileset = (byte)(tid & 0xFF);
        }
    }

    public class Page
    {
        public const uint width = 30;
        public const uint height = 17;
        public const uint layers = 4;

        public byte x;
        public byte y;

        public TileId[, ,] tiles;
        public bool[,] collision;

        public Page()
        {
            tiles = new TileId[layers, height, width];
            collision = new bool[height, width];
        }

        public void Serialize(BinaryWriter writer)
        {
            writer.Write(x);
            writer.Write((byte)(255 - y));

            for (uint i = 0; i < layers; ++i)
                for (uint j = 0; j < height; ++j)
                    for (uint k = 0; k < width; ++k)
                        writer.Write(tiles[i, j, k].ToUInt16());

            for (uint j = 0; j < height; ++j)
                for (uint k = 0; k < width; ++k)
                    writer.Write(collision[j, k]);
        }

        public void Deserialize(BinaryReader reader)
        {
            x = reader.ReadByte();
            y = (byte)(255 - reader.ReadByte());

            for (uint i = 0; i < layers; ++i)
                for (uint j = 0; j < height; ++j)
                    for (uint k = 0; k < width; ++k)
                        tiles[i, j, k].FromUInt16(reader.ReadUInt16());

            for (uint j = 0; j < height; ++j)
                for (uint k = 0; k < width; ++k)
                    collision[j, k] = reader.ReadBoolean();
        }

    }
}
